package com.vhall.component.service.upload.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.vhall.component.plugin.common.utils.UploadUtil;
import com.vhall.component.plugin.core.service.OssService;
import com.vhall.component.service.upload.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yongzheng.xu
 * @date 2021/5/26 19:09
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private OssService ossService;

    private String path = "api_service";

    @Override
    public Map<String, String> doUpload(MultipartFile file, String name) {
        Map<String, String> map = new HashMap<>(4);
        if (StringUtils.isEmpty(name)) {
            name = IdUtil.simpleUUID();
        }
        try {
            String ext = FileNameUtil.extName(file.getOriginalFilename());
            name = name + "." + ext;
            String type = file.getContentType();
            InputStream stream = UploadUtil.multipartFile2InputStream(file);
            String url = ossService.upload(stream, name, type);
            map.put("url", url);
        } catch (Exception ex) {
            log.error("图片上传失败:", ex);
        }
        return map;
    }
}
